package io.renren.modules.generator.service.impl;

import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.CouponDao;
import io.renren.modules.generator.entity.CouponEntity;
import io.renren.modules.generator.service.CouponService;


@Service("couponService")
public class CouponServiceImpl extends ServiceImpl<CouponDao, CouponEntity> implements CouponService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        List<CouponEntity> allCoupons = this.list();
        for (CouponEntity coupon : allCoupons) {
            if (coupon.getDueDate().before(new Date())) {
                this.removeById(coupon.getId());
            }
        }

        IPage<CouponEntity> page = this.page(
                new Query<CouponEntity>().getPage(params),
                new QueryWrapper<CouponEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByUserId(Long userId, Map<String, Object> params) {
        List<CouponEntity> allCoupons = this.list();
        for (CouponEntity coupon : allCoupons) {
            if (coupon.getDueDate().before(new Date())) {
                this.removeById(coupon.getId());
            }
        }

        IPage<CouponEntity> page = this.page(
                new Query<CouponEntity>().getPage(params),
                new QueryWrapper<CouponEntity>().eq("user_id", userId)
        );

        return new PageUtils(page);
    }

    @Override
    public Boolean batchCoupon(CouponEntity couponEntity) {
        List<SysUserEntity> list = sysUserService.list();
        for (SysUserEntity sysUserEntity : list) {
            couponEntity.setUserId(sysUserEntity.getUserId());
            this.save(couponEntity);
        }
        return true;
    }

}